package redis

import (
	"bluebell-backend/common"
	"bluebell-backend/model/vo"
	"github.com/go-redis/redis"
	"strconv"
	"time"
)

// 查询当前分类下的所有postId
func GetPostIdsWithOrder(vo *vo.PostVo) ([]string, error) {
	// 从redis获取postId

	// 获取排序对应的key
	orderKey := GetRedisKey(KeyPostTimeZSet)
	if vo.Order == common.ORDER_SCORE {
		orderKey = GetRedisKey(KeyPostScoreZSet)
	}

	// 获取指定分类的key
	cKey := GetRedisKey(KeyCategorySetPF + strconv.Itoa(int(vo.Cid)))

	// 添加一个缓存，有的话就直接查，没有就添加一个
	key := orderKey + strconv.Itoa(int(vo.Cid))
	if client.Exists(key).Val() < 1 {
		// 说明不存在
		pipeline := client.Pipeline()
		pipeline.ZInterStore(key, redis.ZStore{
			Aggregate: "MAX",
		}, cKey, orderKey) // 利用这个方法将set和zset合并

		// 设置超时时间
		pipeline.Expire(key, 60*time.Second)
		_, err := pipeline.Exec()
		if err != nil {
			return nil, err
		}
	}

	// 存在的话，就直接根据key查询ids
	return getIDsFormKey(key, vo.Page, vo.Size)

}

func getIDsFormKey(key string, page, size int64) ([]string, error) {
	start := (page - 1) * size
	end := start + size - 1

	return client.ZRevRange(key, start, end).Result()
}

// GetPostVoteData 根据ids查询每篇帖子的投赞成票的数据
func GetPostVoteData(ids []string) (data []int64, err error) {

	// 使用管道，减少RTT
	pipeline := client.Pipeline()
	for _, id := range ids {
		// 查找key中分数是1的元素的数量,也就是统计每篇帖子的赞成票的数量
		key := GetRedisKey(KeyPostVotedZSetPF + id)
		pipeline.ZCount(key, "1", "1")
	}
	cmders, err := pipeline.Exec()
	if err != nil {
		return
	}
	data = make([]int64, 0, len(cmders))
	for _, cmder := range cmders {
		v := cmder.(*redis.IntCmd).Val()
		data = append(data, v)
	}
	return
}
